package com.buka.user.controller;

import com.buka.user.entity.User;
import com.buka.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UserLoginServlet extends HttpServlet {

    UserService userService = new UserService();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理字符编码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String userName = req.getParameter("userName");
        String passwd = req.getParameter("passwd");

        //去数据库查询用户是否存在且密码是否正确
        User user = userService.selectByNameAndPasswd(userName,passwd);

        if(null != user){
            //可以登录
            req.getSession().setAttribute("loginUser",user);
            //重定向地址，没有http://的时候相对于项目的根   也就是 http://ip:端口/上下文/当前文件夹/index.html"
            //请求地址 带有/    /index.html      是相对于tomcat的根  （没有上下文）

            resp.sendRedirect("/user/blog/list");

        }else{
            //登录失败，返回信息 用户不存在或密码错误
            String errMsg = "用户不存在或密码错误!";
            String errHtml = "<html> " +
                             "<meta charset=\"UTF-8\">" +
                             "<body> " +
                             "<h1>" + errMsg +
                             "</h1>" +
                             "</body>" +
                             "</html>";
            PrintWriter writer = resp.getWriter();
            writer.print(errHtml);

        }








    }
}
